package com.flywen.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtils {
    public IPUtils() {
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = getIpByHeaderName(request, "x-forwarded-for");
        if (StringUtils.isBlank(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
            if (StringUtils.isBlank(ipAddress)) {
                ipAddress = getIpByHeaderName(request, "WL-Proxy-Client-IP");
                if (StringUtils.isBlank(ipAddress)) {
                    ipAddress = request.getRemoteAddr();
                    if (ipAddress.equals("127.0.0.1") || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                        return "127.0.0.1";
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(ipAddress) && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
            ipAddress = StringUtils.substringBefore(ipAddress, ",");
        }

        return ipAddress;
    }

    public static String getIpByHeaderName(HttpServletRequest httpServletRequest, String headerName) {
        String ipAddress = httpServletRequest.getHeader(headerName);
        ipAddress = !StringUtils.isBlank(ipAddress) && !"unknown".equalsIgnoreCase(ipAddress) ? ipAddress : null;
        return ipAddress;
    }

    public static boolean isInnerIpAddress(String ipAddress) {
        if ("127.0.0.1".equals(ipAddress)) {
            return true;
        } else {
            String reg = "(10|172|192)\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})\\.([0-1][0-9]{0,2}|[2][0-5]{0,2}|[3-9][0-9]{0,1})";
            Pattern p = Pattern.compile(reg);
            Matcher matcher = p.matcher(ipAddress);
            return matcher.find();
        }
    }

    public static String getLocalIpAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress().toString();
        } catch (Exception var1) {
            return null;
        }
    }
}
